package org.os.framework.redis;

import java.io.IOException;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 分布式锁
 * 
 * @author weizuxiao
 */
@Slf4j
@Data
@ConditionalOnProperty(name = "spring.redisson.enable", havingValue = "true")
@ConfigurationProperties(prefix = "spring.redisson")
@Configuration
public class RedissonConfig {

    /**
     * 主机名
     */
    private String host;

    /**
     * 密码
     */
    private String password = "";

    /**
     * 端口
     */
    private Integer port = 6379;

    /**
     * 数据库
     */
    private Integer db = 0;

    /**
     * 最小连接数
     */
    private Integer minimumIdleSize = 5;

    /**
     * 连接池
     */
    private Integer connectionPoolSize = 50;

    /**
     * 重试次数
     */
    private Integer retryAttempts = 5;

    /**
     * 重试间隔
     */
    private Integer retryInterval = 1000;

    /**
     * 心跳间隔
     */
    private Integer pingConnectionInterval = 5000;

    /**
     * 超时时间
     */
    private Integer timeout = 30000;

    @Bean
    public RedissonClient redissonClient() throws IOException {
        log.info("加载redisson配置 = {}", this);
        String addr = new StringBuilder("redis://")
                .append(host)
                .append(":")
                .append(port).toString();
        Config config = new Config();
        config.useSingleServer()
                .setAddress(addr)
                .setDatabase(db)
                .setConnectionMinimumIdleSize(minimumIdleSize)
                .setConnectionPoolSize(connectionPoolSize)
                .setRetryAttempts(retryAttempts)
                .setRetryInterval(retryInterval)
                .setPingConnectionInterval(pingConnectionInterval)
                .setTimeout(timeout);
        if (StringUtils.hasText(password)) {
            config.useSingleServer().setPassword(password);
        }
        RedissonClient redisson = Redisson.create(config);
        return redisson;
    }

}
